import JSZip from 'jszip'
import FileSaver from 'file-saver'
import { ElMessage } from 'element-plus'

export const downloadByBlob = (blob: Blob, fileName: string) => {
  const link = document.createElement('a')
  link.download = fileName
  link.href = window.URL.createObjectURL(blob)
  link.click()
  window.URL.revokeObjectURL(link.href) //释放 url
  link.remove()
  ElMessage.success('下载成功')
}

/**
 * 文件下载（单个或多个）
 * @param filepathData 单个文件路径 | 文件路径数组
 * @param cb 文件下载成功后的回调函数
 */
export const downloadFile = (filepathData: string | string[], cb?: () => void) => {
  if (typeof filepathData === 'string') {
    getFileByUrl(filepathData).then((blob) => {
      const nameArr = filepathData.split('/')
      const fileName = nameArr.at(-1) as string // 获取文件名
      downloadByBlob(blob, fileName)
      ElMessage.success('下载成功')
      cb && cb()
    })
  } else {
    const zip = new JSZip()
    const promises: Promise<void>[] = []
    filepathData.forEach((item) => {
      const promise = getFileByUrl(item).then((data) => {
        const nameArr = item.split('/')
        const fileName = nameArr.at(-1) as string // 获取文件名
        zip.file(fileName, data, { binary: true }) // 逐个添加文件
      })
      promises.push(promise)
    })
    Promise.all(promises).then(() => {
      zip.generateAsync({ type: 'blob' }).then((content) => {
        // 生成二进制流
        FileSaver.saveAs(content, `批量下载-${Date.now()}.zip`) // 利用file-saver保存文件
        ElMessage.success('下载成功')
        cb && cb()
      })
    })
  }
}

// 根据 url 获取文件
export const getFileByUrl = (url: string) => {
  return new Promise<Blob>((resolve, reject) => {
    fetch(url, {
      method: 'GET',
      headers: {
        responseType: 'blob'
      }
    })
      .then((res) => resolve(res.blob()))
      .catch((error) => reject(error.toString()))
  })
}

// 导出 csv 文件
export const exportCsv = <T extends { [key: string]: string }>(obj: {
  titleList: string[]
  data: T[]
}) => {
  // 表头
  const titleList = obj.titleList
  // 获取所有 key
  const dataKeys = Object.keys(obj.data[0])

  const str: string[] = []
  str.push(titleList.join(',') + '\r\n')
  for (let i = 0; i < obj.data.length; i++) {
    const temp = []
    for (let j = 0; j < dataKeys.length; j++) {
      temp.push(obj.data[i][dataKeys[j]])
    }
    str.push(temp.join(',') + '\r\n')
  }
  const blob = new Blob(['\uFEFF' + str.join('')], {
    type: 'text/csv;charset=utf-8'
  })
  downloadByBlob(blob, '导出外链.csv')
}
